package com.turbo.cloud.gateway.utils;

import com.turbo.cloud.gateway.api.R;
import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 验证结果工具类
 * @author zhangluning
 */
public class AuthUtil {

    /**
     * 认证不成功
     *
     * @param resp 返回body
     * @param msg  描述
     * @return
     */
    public static Mono<Void> unSuccessAuth(ServerHttpResponse resp, Integer httpStatus, String msg) {
        resp.setStatusCode(HttpStatus.valueOf(httpStatus));
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = JSONUtil.toJsonStr(R.failed(msg));
        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    /**
     * 认证不成功
     *
     * @param resp 返回body
     * @param msg  描述
     * @return
     */
    public static Mono<Void> unSuccessAuth(ServerHttpResponse resp, String msg) {
        return unSuccessAuth(resp, HttpStatus.FORBIDDEN.value(), msg);
    }
}
